#ifndef __LOG_HPP__
#define __LOG_HPP__

#include <iostream>
#include <cstdio>
#include <string>
#include <filesystem> //C++17
#include <sstream>
#include <fstream>
#include <memory>
#include <ctime>
#include <unistd.h>
#include "Mutex.hpp"

namespace LogModel
{
    using namespace MutexModel;
    const std::string gsep = "\r\n"; // 若主要在 Linux/Unix/MacOS 下使用，换为 \n 更简洁且兼容；
                                     // 若需兼容 Windows 记事本，保留 \r\n 更稳妥。若用 \n，日志会连成一行（或显示为方块）
    // 策略模式
    class LogStragegy
    {
    public:
        ~LogStragegy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };
    class ConsoleLogStragegy : public LogStragegy
    {
    public:
        ConsoleLogStragegy()
        {
        }
        void SyncLog(const std::string &message) override
        {
            Guard lockguard(&_mutex);
            std::cout << message << gsep;
        }
        ~ConsoleLogStragegy() {}

    private:
        Mutex _mutex;
    };

    const std::string defaultpath = "./log";
    const std::string defaultfile = "my.log";

    class FileLogStragegy : public LogStragegy
    {
    public:
        FileLogStragegy(const std::string &path = defaultpath, const std::string &file = defaultfile)
            : _path(path), _file(file)
        {
            Guard lockguard(&_mutex);
            if (std::filesystem::exists(_path))
                return;
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << gsep;
            }
        }
        void SyncLog(const std::string &message) override
        {
            Guard lockguard(&_mutex);
            std::string filename = _path + (_path.back() == '/' ? "" : "/") + _file;
            std::ofstream out(filename, std::ios_base::app);
            if (!out.is_open())
            {
                return;
            }
            out << message << gsep;
            out.close();
        }

        ~FileLogStragegy() {}

    private:
        std::string _path;
        std::string _file;
        Mutex _mutex;
    };

    // 日志等级
    enum class LogLevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    std::string Level_Str(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }
    std::string GetTimeStamp()
    {
        time_t curr = time(nullptr);
        struct tm curr_tm;
        localtime_r(&curr, &curr_tm);
        char timebuffer[128];
        snprintf(timebuffer, sizeof(timebuffer), "%4d-%02d-%02d %02d:%02d:%02d",
                 curr_tm.tm_year, curr_tm.tm_mon, curr_tm.tm_mday, curr_tm.tm_hour, curr_tm.tm_min, curr_tm.tm_sec);
        return timebuffer;
    }
    class Logger
    {
    public:
        Logger()
        {
            SelectFileLogStragegy();
        }
        void SelectFileLogStragegy(const std::string &path = defaultpath, const std::string &file = defaultfile)
        {
            _fflush_strategy = std::make_unique<FileLogStragegy>(path, file);
        }
        void SelectConsoleLogStragegy()
        {
            _fflush_strategy = std::make_unique<ConsoleLogStragegy>();
        }
        ~Logger()
        {
        }
        class LogMessage
        {
        public:
            LogMessage(LogLevel level, std::string &src_name, int line, Logger &logger)
                : _level(level), _name(src_name), _line(line), _logger(logger), _curr_time(GetTimeStamp()), _pid(getpid())
            {
                std::stringstream ss;
                ss << "[" << _curr_time << "]"
                   << "[" << Level_Str(_level) << "]"
                   << "[" << _name << "]"
                   << "[" << _line << "]"
                   << "[" << _pid << "]" << "-";
                _loginfo = ss.str();
            }
            template <class T>
            LogMessage& operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }
            ~LogMessage()
            {
                _logger._fflush_strategy->SyncLog(_loginfo);
            }

        private:
            std::string _curr_time;
            LogLevel _level;
            pid_t _pid;
            std::string _name;
            int _line;
            std::string _loginfo;
            Logger &_logger;
        };
        LogMessage operator()(LogLevel level, std::string name, int line)
        {
            return LogMessage(level, name, line, *this);
        }

    private:
        std::unique_ptr<LogStragegy> _fflush_strategy;
    };

    Logger logger;

#define Log(level) logger(level, __FILE__, __LINE__)
#define Enable_Console_Log_Strategy() logger.SelectConsoleLogStragegy()
#define Enable_File_Log_Strategy() logger.SelectFileLogStragegy()
}
#endif